// import Stream from 'node-rtsp-stream'
// const stream = new Stream({
//   name: 'name',
//   streamUrl: 'rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov',
//   wsPort: 9999,
//   ffmpegOptions: { // options ffmpeg flags
//     '-stats': '', // an option with no neccessary value uses a blank string
//     '-r': 30 // options with required values specify the value after the key
//   }
// })
// ffmpeg -i rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov -y -f mjpeg -t 0.001 -s 1280x720 test.jpg
// ffmpeg -i rtsp://172.16.10.123:8557/h264 -y -f mjpeg -t 0.001 test.jpg
// ffmpeg -i http://gb28181.wechain360.com/live/34020000001310000404.m3u8?auth_key=1630253621-0-0-9009a2ecd9caadd275b677d515afe24b -y -f mjpeg -t 0.001 test.jpg
import log from "./logger"
import {Rtsp} from "./interfaces";
import settings from "./settings";
import {axios, EventEmitter, ffmpeg, FormData} from "../node-test";

class RtspImpl extends EventEmitter implements Rtsp {

    public constructor() {
        super();
    }

    init() {
    }

    uploadOss2(file: any): Promise<string> {
        return new Promise((resolve, reject) => {
            const data = new FormData();
            const stream = require('stream');
            const bufferStream = new stream.PassThrough();
            const streams = bufferStream.end(file);
            data.append('contractFile', streams, {filename: 'img.jpg'});
            axios.post(
                settings.url + '/api/account/oss/oss2',
                data,
                {headers: data.getHeaders()}
            ).then(function (response) {
                resolve(response.data.data);
            }).catch(function () {
                reject("uploadOss2 error");
            });
        });
    }

    get_camera_snapshot(rtsp: string, carNum: string, weight: number, time: string): Promise<Buffer> {
        return new Promise((resolve, reject) => {
            try {
                let chunks: any[] = [];
                let size = 0;
                let outOption = "-vf [in]drawtext=x=10:y=300:fontfile=C\\\\:/Windows/fonts/simhei.ttf:fontsize=60:fontcolor=orange:shadowy=2:text=" + carNum + "(" + weight + "吨)," +
                    "drawtext=x=10:y=400:fontfile=C\\\\:/Windows/fonts/simhei.ttf:fontsize=60:fontcolor=orange:shadowy=2:text=" + time + "[text];" +
                    "movie=logo.png[wm];[text][wm]overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)[out]";
                let proc = ffmpeg(rtsp)
                    .inputOptions([
                        "-timeout 2000000",
                        "-f rtsp",
                        "-rtsp_transport tcp",
                        "-an"
                    ])
                    .outputOptions([
                        outOption,
                        "-vframes 1"
                    ])
                    .format('mjpeg')
                    .on('end', async function () {
                        let data = Buffer.concat(chunks, size);
                        // let base64_img = data.toString('base64');
                        resolve(data);
                    })
                    .on('error', function (err) {
                        log.error('an error happened on get_camera_snapshot:' + err.message);
                        reject();
                    })
                let ffstream = proc.pipe();
                ffstream.on('data', function (chunk) {
                    chunks.push(chunk);
                    size += chunk.length;
                });
            } catch (error) {
                log.error('---get camera snapshot failed---', error);
                reject();
            }
        })
    }

    async saveImg(inout: string, carNum: string, weight: number, time: string) {
        const photo = {
            deviceSerial: "",
            picUrl: ""
        };
        const photoList: string[] = [];
        for (let vlpr of settings.dvr) {
            try {
                const file = await this.get_camera_snapshot(vlpr.rtsp, carNum, weight, time)
                const imgUrl = await this.uploadOss2(file);
                photoList.push(imgUrl)
                let deviceSerialNumber = vlpr.deviceSerialNumber;
                let direction = vlpr.direction;
                if (deviceSerialNumber && deviceSerialNumber !== '' && direction && direction !== '' && direction === inout) {
                    photo.deviceSerial = deviceSerialNumber;
                    photo.picUrl = imgUrl;
                }
            } catch (e) {
                log.error(e);
            }
        }
        return {
            photo: photo,
            photoList: photoList
        };
    }
}

const rtsp = new RtspImpl();
export default rtsp;